package me.yangteng.zhihudaily.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import me.yangteng.zhihudaily.R;
import me.yangteng.zhihudaily.activity.StoryDetailActivity;
import me.yangteng.zhihudaily.component.NewsListAdapter;
import me.yangteng.zhihudaily.component.ScrollListenerView;
import me.yangteng.zhihudaily.component.ScrollViewAdapter;
import me.yangteng.zhihudaily.model.LatestNews;
import me.yangteng.zhihudaily.model.StoriesList;
import me.yangteng.zhihudaily.util.CachedStoryFetcher;
import me.yangteng.zhihudaily.util.Helper;
import me.yangteng.zhihudaily.util.HttpLoader;
import me.yangteng.zhihudaily.util.LocalStoryLoader;
import me.yangteng.zhihudaily.util.Url;

/**
 * A simple {@link Fragment} subclass.
 */
public class IndexPageFragment extends Fragment {

  private static final String TAG = "IndexPageFragment";

  private Gson gson;
  private ListView newsListView;
  private View view;
  private LatestNews latestNews;
  private SwipeRefreshLayout mainSwipeLayout;
  private ScrollListenerView mainScrollView;
  private RollPagerView mainBannerViewPager;
  private Context context;
  private CachedStoryFetcher cachedStoryFetcher;
  // 是否正在获取列表
  private boolean isFetchingNews = false;
  private Calendar dateBefore;
  private LocalStoryLoader localStoryLoader;

  private List<StoriesList> storiesLists;

  public IndexPageFragment() {
    // Required empty public constructor
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gson = new Gson();
    dateBefore = Calendar.getInstance();
    cachedStoryFetcher = new CachedStoryFetcher(getContext());
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    Log.d(TAG, "IndexPageFragment on create view");
    Log.d(TAG, Helper.simpleDateFormat.format(dateBefore.getTime()));

    if (this.view == null) {
      this.view = inflater.inflate(R.layout.fragment_index_page, container, false);
    }
    storiesLists = new ArrayList<>();
    newsListView = this.view.findViewById(R.id.newsListView);
    mainSwipeLayout = this.view.findViewById(R.id.mainSwipeLayout);
    mainScrollView = this.view.findViewById(R.id.mainScrollView);
    mainBannerViewPager = this.view.findViewById(R.id.headerViewPager);
    context = getContext();
    localStoryLoader = new LocalStoryLoader(context);

    initLatestNews();
    fetchLatestNews();
    fetchYesterdayNews();
    initSwipeRefreshLayout();

    // Inflate the layout for this fragment
    return view;
  }

  private void initSwipeRefreshLayout() {
    // 设置下拉刷新动作
    mainSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh() {
        mainSwipeLayout.setRefreshing(true);
        fetchLatestNews();
      }
    });

    mainScrollView.setOnScrollListener(new ScrollListenerView.OnScrollListener() {
      @Override
      public void onScrollToTop() {
        Log.d(TAG, "On scrollView Scroll to top");
      }

      @Override
      public void onScrollToBottom() {
        Log.d(TAG, "On scrollView Scroll to bottom");
        fetchYesterdayNews();
      }
    });
  }

  private void initLatestNews() {
    if (localStoryLoader.has(LatestNews.STORAGE_PREFIX)) {
      LatestNews storageLatestNews = gson.fromJson(localStoryLoader.load(LatestNews.STORAGE_PREFIX), LatestNews.class);
      if (storageLatestNews.getDate().equals(Helper.simpleDateFormat.format(dateBefore.getTime()))) {
        latestNews = storageLatestNews;
        renderLatestNews();
      }
    }
  }

  private void fetchLatestNews() {
    Log.d(TAG, "Fetch latestNews");

    Log.d(TAG, "Current Date " + Helper.simpleDateFormat.format(dateBefore.getTime()));
    HttpLoader httpLoader = new HttpLoader();
    httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
      @Override
      public void onGetHttpString(String string) {
        Log.d(TAG, string);
        latestNews = gson.fromJson(string, LatestNews.class);
        latestNews.setDateTitle("今日热文");
        localStoryLoader.save(latestNews);
        renderLatestNews();
        cachedStoryFetcher.fetchStories(latestNews);
      }

      @Override
      public void onError(Exception e) {
        HttpLoader.onErrorHandler(view);
      }
    });
    httpLoader.execute(Url.LATEST_STORIES_LIST);
  }

  private void renderLatestNews() {
    if (storiesLists.size() > 0) {
      if (!storiesLists.get(0).getDate().equals(latestNews.getDate())) {
        Log.d(TAG, "Reload view");
        storiesLists = new ArrayList<>();
        storiesLists.add(latestNews);
        dateBefore = Calendar.getInstance();
        fetchYesterdayNews();
      } else {
        storiesLists.set(0, latestNews);
      }
    } else {
      storiesLists.add(latestNews);
    }
    newsListView.setAdapter(new NewsListAdapter(getActivity(), storiesLists));
    mainSwipeLayout.setRefreshing(false);
    renderBannerViewPager();
  }

  private void fetchYesterdayNews() {
    if (this.isFetchingNews) return;
    this.isFetchingNews = true;
    final String yesterdayString = getYesterday();
    if (localStoryLoader.has(StoriesList.STORAGE_PREFIX + yesterdayString)) {
      renderYesterdayNews(gson.fromJson(localStoryLoader.load(StoriesList.STORAGE_PREFIX + yesterdayString), StoriesList.class));
    } else {
      HttpLoader httpLoader = new HttpLoader();
      httpLoader.setHttpLoaderListener(new HttpLoader.HttpLoaderListener() {
        @Override
        public void onGetHttpString(String string) {
          Log.d(TAG, string);
          StoriesList currentStoriesList = gson.fromJson(string, StoriesList.class);
          currentStoriesList.setDateTitle(renderDateTitle(currentStoriesList.getDate()));
          currentStoriesList.setStorageKey(StoriesList.STORAGE_PREFIX + yesterdayString);
          localStoryLoader.save(currentStoriesList);
          cachedStoryFetcher.fetchStories(currentStoriesList);
          renderYesterdayNews(currentStoriesList);
        }

        @Override
        public void onError(Exception e) {
          HttpLoader.onErrorHandler(view);
        }
      });
      httpLoader.execute(Url.STORIES_LIST_BY_DATE + yesterdayString);
    }
  }

  private void renderYesterdayNews(StoriesList currentStoriesList) {
    storiesLists.add(currentStoriesList);
    isFetchingNews = false;
    Helper.setListViewHeightBasedOnChildren(newsListView);
  }

  private String getYesterday() {
    String yesterday = Helper.simpleDateFormat.format(dateBefore.getTime());
    dateBefore.add(Calendar.DATE, -1);
    return yesterday;
  }

  private String renderDateTitle(String date) {
    char[] dateArr = date.toCharArray();
    String month = dateArr[4] == '0' ? dateArr[5] + "" : dateArr[4] + "" + dateArr[5];
    String day = dateArr[6] == '0' ? dateArr[7] + "" : dateArr[6] + "" + dateArr[7];
    return month + "月" + day + "日";
  }

  private void renderBannerViewPager() {
    mainBannerViewPager.setAdapter(new ScrollViewAdapter(latestNews.getTop_stories(), this.getContext()));
    mainBannerViewPager.setHintView(new ColorPointHintView(this.getContext(), Color.parseColor("#FFFFFF"), Color.parseColor("#88ffffff")));
    mainBannerViewPager.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(int position) {
        Intent intent = new Intent(context, StoryDetailActivity.class);
        intent.putExtra("storyId", latestNews.getTop_stories().get(position).getId() + "");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
      }
    });
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    if (view != null) {
      ((ViewGroup) view.getParent()).removeView(view);
    }
  }
}
